package com.art.wisdom.impl.user;

import java.net.URLEncoder;
import java.sql.Date;
import java.text.SimpleDateFormat;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.art.wisdom.api.user.IUserService;
import com.art.wisdom.mapper.UserMapper;
import com.art.wisdom.model.User;
import com.art.wisdom.util.Result;
import com.art.wisdom.util.ResultStatus;

/**
 * 
 * @author xiezhiwei
 * @email xiezhiwei0314@126.com
 * @date 2017-08-10
 * 
 */
@Service
public class UserServiceImpl implements IUserService {
	
	private Logger logger = Logger.getLogger(UserServiceImpl.class);
	
	@Autowired
	private TransactionTemplate transactionTemplate;
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public Result<User> getUserInfo(String openId) {
		
		return null;
	}

	@Override
	public Result<User> getUserByIdInfo(String userId) {
		Result<User> result = new Result<User>();
		try{
			User user = userMapper.getUserByIdInfo(userId);
			result.setResult(ResultStatus.SUCCESS, user, "查询用户信息成功");
		}catch (Exception e) {
			logger.info(e.getMessage());
			result.setResult(ResultStatus.ERROR, null, "查询用户信息失败");
		}
		return result;
	}

	@Override
	public Result<User> addUserInfo(final User user) {
		final Result<User> result=new Result<User>();
		transactionTemplate.execute(new TransactionCallback<Result<User>>() {

			@Override
			public Result<User> doInTransaction(TransactionStatus status) {
				try{
					User newUser = userMapper.insertUserInfo(user);
		        	if(newUser==null){
		        		throw new Exception("用户信息插入失败");
		        	}
	
		           result.setResult(ResultStatus.SUCCESS,newUser, "用户信息新增成功");
		           
				}catch(Exception e){
					logger.debug(e.getMessage());
					e.printStackTrace();
					status.setRollbackOnly();
				}
				return result;
			}
			
		});
		
		return result;
	}

}
